define(["../common"], function() {

	var $form = $("#prepaidForm");
	var checkUserPath = g_shopDomain + "/memberVip/balance/json";
	var prepaidDoPath = g_shopDomain + "/memberPrepaid/prepaidDo/json";
	var registerPath = g_shopDomain + "/member/register";

	$("[id^='submitBt_']").click(function() {
		$form.trigger('validate');
	});

	// 事件:进入会员注册
	$(document).on('click', "#regBt", function() {
		location.href = registerPath;
	});

	// 解决焦点在用户名表单时，“点击注册”要点两次才起效的问题
	$(document).on('mouseover', "#regBt", function() {
		if ($("#userName").is(":focus")) {// 没有此句将无法触发以下的mouseout
			$("#userName").blur();
		}
	});
	$(document).on('mouseout', "#regBt", function() {
		$("#userName").focus();
	});
	
	$form.on('valid.form', function(e, form) {
		if(!$(form).showMsg("充值中...", 'load', true)) return;
		
		$.post(prepaidDoPath, $(form).serialize(), function(data) {
			if (data.status !== 0) {
				$(form).showMsg(data.message, 'error', -1);
				return;
			}
			$(form).showMsg("充值成功！", 'pass');
			
			$("[name='prepaid']").val("");
			if ($("#userName").val()) {
				checkName();
			}
		});
	});

	loadjs(["validator"],function() {
		$form.validator({
			rules: {
				checkName: checkName,
				checkPrepaid: checkPrepaid
			},
			fields: {
				userName: {
					rule: "required;checkName",
					msg: {
						checkName: "用户不存在，<a id='regBt' style='color:#06F'>点击注册</a>"
					}
				},
				prepaid: {
					rule: "required;integer[+];range[1~2000],checkPrepaid"
				}
			}
		});
	});
	
	function checkName() {
		return $.post(checkUserPath, {userName: $("#userName").val()}, function(data){
			if (!data.error) {
				data.canPrepaid = data.canPrepaid < 0 ? 0: data.canPrepaid;
				// 缓存结果
				$(document).data("prepaidData", data);
				
				$("#balanceTip").html("您的当前余额为 " + data.balance + " 元，还可以充值 " + data.canPrepaid + " 元");
				$("#balanceTip").parent("p").show();
				
			} else {
				// 缓存结果
				$(document).removeData("prepaidData");
				
				$("#balanceTip").parent("p").hide();
			}
			
			$("[name='prepaid']").trigger('keyup');
		});
	}

	function checkPrepaid(el, param, field) {
		// 见checkName()
		var pd = $(document).data("prepaidData");
		if (!pd) {
			return;
		}
		if (parseInt($(el).val()) > parseInt(pd.canPrepaid)) {
			return "最多还可充值" + pd.canPrepaid + "元";
		}
			
	}

	// 优惠计算相关
	$(function() {
		
		var curPrepaid = 0;// 充值金额
		var $favorable = $("#favorable");
		
		$("[name='prepaid']").blur(prepaidCallback_)
		$("[name='prepaid']").keyup(prepaidCallback_);	
		
		function prepaidCallback_() {
			$favorable.empty().parent("p").hide();
			
			// 缓存见checkName()
			var pd = $(document).data("prepaidData");
			if (!pd) {
				return;
			}
			
			curPrepaid = parseFloat($(this).val());
			if (isNaN(curPrepaid)) {
				return;
			}
			
			// 从缓存中获取促销信息（缓存见充值优惠说明相关功能）
			var mps = $(document).data("mps");// memberPromotes
	  		if (!mps) {
	  			return;
	  		}	
	        
			// 检查充值金额优惠
			// 检查累计充值优惠
			// 检查最高充值优惠
			var mpList,mp,destPrepaid,holdMp,has;
			
			for (var type in mps) {
				mpList = mps[type];
				
				if (type === "0") {
					destPrepaid = curPrepaid;
				} else if (type === "1") {
					destPrepaid = pd.prepaidTotal + curPrepaid;
				} else if (type === "2") {
					destPrepaid = curPrepaid > pd.prepaidMax ? curPrepaid : pd.prepaidMax;
				}
				
				holdMp = null;
				for (var i in mpList) {// 前提是mpList已经按prepaid由小到大排序
					mp = mpList[i];
					if (destPrepaid >= mp.prepaid) {
						holdMp = mp;
					} else {
						break;
					}
				}
	          	if (!holdMp) {
	          		continue;
	          	}
				
				if (has) {
					$favorable.append('<br>');
				} else {
					$favorable.parent("p").show();
					has = true;
				}
				
				if (type === "0") {
					$favorable.append('<span style="float:left;">每次充值（' + destPrepaid + '元）满：' + holdMp.prepaid + '元 送 <i style="color:red;">' + holdMp.give + '</i> 元</span>');
				} else if (type === "1") {
					$favorable.append('<span style="float:left;">累计充值（' + destPrepaid + '元）满：' + holdMp.prepaid + '元 送 <i style="color:red;">' + holdMp.give + '</i> 元</span>');
				} else if (type === "2") {
					$favorable.append('<span style="float:left;">最高充值（' + destPrepaid + '元）满：' + holdMp.prepaid + '元 打 <i style="color:red;">' + holdMp.give + '</i> 折</span>');
				}  			
			}
		}
	});

	// 充值优惠说明相关
	$(function() {
		var memPromote = parseInt($("#d_memPromote").html());
		
		if (memPromote > 0) {
			$("#promoteInfo").fadeIn();
		}
		
		$("[id^='type_']").each(function(i, el) {
			var type = ($(this).attr("id").split("_"))[1];
	    	if ((memPromote & (1 << type)) > 0) {
	    		loadPromote_(type);
	    	}
	    });
	    
	    function loadPromote_(type) {
	    	$.get(g_shopDomain + "/memberPromote/list/json", {type: type}, function(data) {
	        	if (data.status !== 0) {
	        		$(document).showMsg(data.message, 'error');
	        		return;
	        	}
	        	
	        	// 促销信息
	        	var mps = $(document).data("mps");// memberPromotes
	        	if (!mps) {
	        		mps = {};
	        	}
	        	mps[type] = data.result;
	        	// 缓存
	        	$(document).data("mps", mps);
	        	
	        	var list = data.result;
	        	if (!list) {
	        		return;
	        	}
	        	
	        	var $content = $("#type_" + type).show();
	        	for (var i in list) {
	        		// list[i] -> memberPromote
	        		$content.append(list[i].prepaid  + "元 " + (type === "2" ? "打 " : "送 ") + list[i].give + (type === "2" ? "折；" : "元；"));
	        	}
	        	
	        });
	    }
	});
});
